//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package tasks

import (
	"context"
	"encoding/json"

	bg_runner_core "atomgit.com/openlinksaas/api-server/bg_runner/core"
	"atomgit.com/openlinksaas/api-server/dao/fs_dao"
	"atomgit.com/openlinksaas/api-server/dao/org_dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/extension-proto-gen-go.git/extension_fs_api"
	"go.uber.org/zap"
)

type OrgForumFsClean struct {
	OrgId        string `json:"orgId"`
	ForumId      string `json:"forumId"`
	FsId         string `json:"fsId"`
	FsRemoteAddr string `json:"fsRemoteAddr"`
}

func (t *OrgForumFsClean) TaskType() string {
	return "OrgForumFsClean"
}

func (t *OrgForumFsClean) Execute(logger *zap.Logger) error {
	exist, err := org_dao.OrgInfoDao.Exist(context.Background(), t.OrgId)
	if err != nil {
		return err
	}
	if !exist {
		return nil
	}
	exist, err = org_dao.ForumDao.Exist(context.Background(), t.OrgId, t.ForumId)
	if err != nil {
		return err
	}
	if !exist {
		return nil
	}
	exist, err = fs_dao.FsInfoDao.Exist(context.Background(), t.FsId)
	if err != nil {
		return err
	}
	if !exist {
		return nil
	}
	conn, err := utils.ConnGrpc(t.FsRemoteAddr)
	if err != nil {
		return err
	}
	defer conn.Close()

	client := extension_fs_api.NewExtensionFsApiClient(conn)

	for {
		fileItemList, err := fs_dao.FsFileDao.ListByFsId(context.Background(), t.FsId, 1000)
		if err != nil {
			return err
		}
		if len(fileItemList) == 0 {
			break
		}
		for _, fileItem := range fileItemList {
			client.RemoveFile(context.Background(), &extension_fs_api.RemoveFileRequest{
				FsId:   fileItem.FsId,
				FileId: fileItem.FileId,
			}) //skip error check
			err = fs_dao.FsFileDao.Remove(context.Background(), t.FsId, fileItem.FileId)
			if err != nil {
				return err
			}
		}
	}
	err = fs_dao.FsInfoDao.Remove(context.Background(), t.FsId)
	if err != nil {
		return err
	}
	return nil
}
func (t *OrgForumFsClean) NewInstance(jsonData []byte) (bg_runner_core.BackGroundTask, error) {
	obj := &OrgForumFsClean{}
	err := json.Unmarshal(jsonData, obj)
	if err != nil {
		return nil, err
	}
	return obj, nil
}
